package com.wzcl.app.dao.repository;

import com.wzcl.app.dao.model.Course;
import org.apache.catalina.LifecycleState;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


public interface CourseRepository extends JpaRepository<Course,Integer>, JpaSpecificationExecutor<Course> {

    @Query("SELECT m FROM Course m WHERE m.commodity.id = ?1 AND m.state = 0")
    Course findByCommodityId(Integer id);

    /**
     * 对指定类型的课程进行模糊查询
     * @param name 模糊查询字段
     * @return 返回查询结果
     */
    @Query("select c from Course c where (c.courseType = 1 or c.courseType = 2 or c.courseType = 4 or c.courseType = 10) and c.state = 1 and c.name like %?1%")
    List<Course> findBySomeType(String name);

    /**
     * 通过课程name查找id
     * @param courseName 课程名称
     * @return 返回课程id
     */
    @Query("SELECT cou FROM Course cou WHERE cou.name = :courseName")
    Course findCourseByCourseName(@Param("courseName") String courseName);

    /**
     * 根据id查询课程
     * @param id 课程id
     * @return
     */
    @Query(value = "select cou from Course cou where cou.id = ?1")
    Course findAllByCourseId(Integer id);

    //通过课程id查询学科id
    @Query(value = "SELECT cou.subject.id FROM Course cou WHERE cou.id = ?1")
    Integer findSubjectIdByCourseId(Integer courseId);

    //根据课程类型查询课程
    @Query(value = "select cou from Course cou where cou.courseType = ?1")
    List<Course> getCourseByCourseType(Integer courseType);

    //更新观看人数
    @Query(value = "update Course  cou set cou.viewVolume = ?1 where cou.id = ?2")
    @Modifying
    @Transactional
    void updateViewVolume(Integer viewVolume, Integer id);

    //更新观看人数
    @Query(value = "update Course  cou set cou.viewVolume = ?1 where cou.name like %?2% and cou.name like %?3%")
    @Modifying
    @Transactional
    void updateViewVolumeByName(Long viewVolume, String name1, String name2);

    //根据课程名模糊查询课程
    @Query(value = "select distinct c.grade.id from Course c where c.name like ?1")
    List<Integer> findByCourseName(String name);
}